package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.AttendanceRecord;
import org.example.entity.CardReplacementApplication;
import org.example.models.R;
import org.example.service.AttendanceRecordService;
import org.example.service.CardReplacementApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @Author: 鸢一折纸
 * @Email: 3498881048@qq.com
 * @Date: 2025/09/11 8:57
 * @Description:
 **/

@RestController
@RequestMapping("/cardReplacementApplication")
public class CardReplacementApplicationController {

    @Autowired
    private CardReplacementApplicationService cardReplacementApplicationService;
    @Autowired
    private AttendanceRecordService attendanceRecordService;

    @GetMapping("/page")
    public R<Page<CardReplacementApplication>> getAllCardReplacementApplication(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "4") int size,
            @RequestParam(name = "userId", required = false) Integer userId,
            @RequestParam(name = "applicationDate", required = false) String applicationDate
    ) {
        QueryWrapper<CardReplacementApplication> query = new QueryWrapper<>();
        query.lambda().eq(CardReplacementApplication::getUserId, userId);
        if (applicationDate != null && !applicationDate.isEmpty()) {
            query.lambda().like(CardReplacementApplication::getApplicationDate, applicationDate);
        }
        query.lambda().orderByDesc(CardReplacementApplication::getApplicationDate);

        Page<CardReplacementApplication> page = new Page<>(current, size);

        cardReplacementApplicationService.page(page, query);
        return R.success(page);
    }

    @PostMapping("/insert")
    public R insert(@RequestBody CardReplacementApplication cardReplacement, @RequestAttribute("userId") Integer userId) {
        // 校验当月补卡次数
        QueryWrapper<CardReplacementApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(CardReplacementApplication::getUserId, userId)
                //添加自定义sql片段，将application_date字段格式化为年-月格式与当前日期进行比较
                .apply("DATE_FORMAT(application_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')");

        long count = cardReplacementApplicationService.count(queryWrapper);
        if (count >= 5) {
            return R.error("当前周期补卡次数已用尽");
        }

        if (cardReplacement != null && userId != null) {
            cardReplacement.setUserId(userId);
        }

        // 保存补卡申请
        boolean result = cardReplacementApplicationService.save(cardReplacement);

        // 如果保存成功，更新考勤记录
        if (result) {
            updateAttendanceRecord(cardReplacement, userId);
            return R.success("已提交申请");
        } else {
            return R.error("提交失败");
        }
    }

    private void updateAttendanceRecord(CardReplacementApplication cardReplacement, Integer userId) {
        Date retroactiveDate = cardReplacement.getRetroactiveDate();
        String cardType = (String) cardReplacement.getTimeBucket(); // 假设有字段标识是上午还是下午

        QueryWrapper<AttendanceRecord> attendanceQuery = new QueryWrapper<>();
        attendanceQuery.lambda()
                .eq(AttendanceRecord::getUserId, userId)
                .eq(AttendanceRecord::getRecordDate, retroactiveDate);

        AttendanceRecord attendanceRecord = attendanceRecordService.getOne(attendanceQuery);

        if (attendanceRecord != null) {
            if ("上午签到".equals(cardType)) {
                attendanceRecord.setMorningStatus("补签");
            } else if ("下午签退".equals(cardType)) {
                attendanceRecord.setAfternoonStatus("补签");
            }
            attendanceRecordService.updateById(attendanceRecord);
        }
    }

}
